#!/bin/bash
###
 # @Author: dvlproad dvlproad@163.com
 # @Date: 2023-02-25 02:04:22
 # @LastEditors: dvlproad dvlproad@163.com
 # @LastEditTime: 2023-02-26 01:36:20
 # @FilePath: /AutoPackage-CommitInfo/bulidScriptCommon/brances_info/all_branch_info_deal.sh
 # @Description: 获取当前分支所包含的分支及其分支信息
### 
:<<!
获取当前分支所包含的分支及其分支信息
ignoreAddJsonFileNames=("dev_demo.json")
ignoreCheckBranchNameArray=(master development dev_publish_out dev_publish_in dev_all)
sh ./brances_info/all_branch_info_deal.sh -envInfoF "../example_packing_info/app_info.json" -appBranchsDir "../example_packing_info/featureBrances" -branchInfoF "../example_packing_info/app_branch_info.json" -ignoreAddJsonFileNames "${ignoreAddJsonFileNames}" -ignoreCheckBranchs "${ignoreCheckBranchNameArray[*]}"
!
User=`whoami`

JQ_EXEC=`which jq`

# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

function logSuccessMsg() {
    printf "${GREEN}----------------  $1  ----------------${GREEN}\n${NC}"
    # echo "----------------------------.feature_brances----------------------------"
}

function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}

# echo "===========进入脚本$0==========="


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


#if [ $# != 5 ]; then
#    echo "当前参数个数$#，必须为5个，请设置更新说明"
#    exit 1
#fi


# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute}/..
bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
#echo "bulidScriptCommon_dir_Absolute=${bulidScriptCommon_dir_Absolute}"

qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_branchMapsFile_checkMap_script_path="$(sh ${qscript_path_get_filepath} qbase branchMapsFile_checkMap)"

bulidScriptBranch_dir_Absolute="${bulidScriptCommon_dir_Absolute}/brances_info"
Update_code_message_SCRIPT_PATH="${bulidScriptCommon_dir_Absolute}/base/error_code_message/update_code_message.sh"

# shell 参数具名化
show_usage="args: [-envInfoF, -rebaseBranch, -appBranchsDir, -branchInfoF, -ignoreAddJsonFileNames, -ignoreCheckBranchs]\
                                  [--environment-info-json-file=, --rebase-branch=, --app-feature-brances-dir=, --branch-info-json-file=, --ignoreAddJsonFileNames=, --ignoreCheck-branchNameArray=]"
# 获取当前分支所包含的分支及其分支信息
while [ -n "$1" ]
do
        case "$1" in
                # 用于获取当前分支的打包环境
                -envInfoF|--environment-info-json-file) Environment_FILE_PATH=$2; shift 2;;
                # 用于获取合入当前分支的有哪些
                -rebaseBranch|--rebase-branch) REBASE_BRANCH=$2; shift 2;;
                # 分支信息源文件夹
                -appBranchsDir|--app-feature-brances-dir) App_Feature_Brances_Directory_PATH=$2; shift 2;;
                # 从appBranchsDir中获取的分支要存放到的文件/存放所有整理后的分支信息源的文件。同时会将此文件的路径设置到打包环境所在的文件中，以备通过一个环境文件找到更多更具体的打包信息。
                -branchInfoF|--branch-info-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
                # 不添加appBranchsDir中的哪些文件，如demo.json
                -ignoreAddJsonFileNames|--ignoreAddJsonFileNames) ignoreAddJsonFileNames=$2; shift 2;;
                # 不对哪些分支进行提测时间等字段的检查，如果要都不检查，可传入"ignoreAllCheck"
                -ignoreCheckBranchs|--ignoreCheck-branchNameArray) ignoreCheckBranchNameArray=$2; shift 2;;
                # 子项的 verbose 的参数，默认无。
                -verboseSubitem|--verbose-subitem) verboseParamForSubitem=$2; shift 2;;
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done


if [ ! -f "${Develop_Branchs_FILE_PATH}" ]; then
    echo "❌Error:从appBranchsDir中获取的分支要存放到的分支文件【${Develop_Branchs_FILE_PATH}】不存在，请先设置！"
    exit_script
fi

sh ${qbase_update_json_file_singleString_script_path} -jsonF "${Environment_FILE_PATH}" -k "developBranchsJsonFile" -v "${Develop_Branchs_FILE_PATH}"
if [ $? != 0 ]; then
    echo "❌Error:存储developBranchsJsonFile失败"
    exit_script
fi

CommonScriptResultJSONFilePath="${bulidScriptCommon_dir_Absolute}/json/common_script_result.json"
if [ ! -f "${CommonScriptResultJSONFilePath}" ]; then
    echo "❌Error:存储错误信息的文件CommonScriptResultJSONFilePath=${CommonScriptResultJSONFilePath}文件不存在，请检查"
fi
# 获取featureBrances文件夹下的所有分支json组成数组，添加到${Develop_Branchs_FILE_PATH}的feature_brances中
printf "${YELLOW}正在执行命令(获取指定文件夹下的所有json分支信息源文件，然后将其设置进指定文件的指定.feature_brances属性中，备后续提取使用)：《 ${BLUE}sh ${bulidScriptBranch_dir_Absolute}/read_and_manager_feature_brances.sh -appBranchsDir \"${App_Feature_Brances_Directory_PATH}\" -branchInfoF \"${Develop_Branchs_FILE_PATH}\" -ignoreAddJsonFileNames \"${ignoreAddJsonFileNames}\" 
-scriptResultJsonF \"${CommonScriptResultJSONFilePath}\" \"${verboseParamForSubitem}\" ${YELLOW}》${NC}\n"
sh ${bulidScriptBranch_dir_Absolute}/read_and_manager_feature_brances.sh -appBranchsDir "${App_Feature_Brances_Directory_PATH}" -branchInfoF "${Develop_Branchs_FILE_PATH}" -ignoreAddJsonFileNames "${ignoreAddJsonFileNames}" -scriptResultJsonF "${CommonScriptResultJSONFilePath}" "${verboseParamForSubitem}"
if [ $? != 0 ]; then
    echo "❌Errror:read_and_manager_feature_brances 执行出错了。。。"
    exit_script
fi
logSuccessMsg "恭喜:最后的 .feature_brances 值如下"
cat ${Develop_Branchs_FILE_PATH} | jq ".feature_brances" | jq '.'
if [ "$(cat ${Develop_Branchs_FILE_PATH} | jq ".feature_brances" | jq '.')" == null ]; then
    echo "${YELLOW}🌶🌶 Warning: 由于未获取到包含所有分支详细信息的文件中有任何开发分支的分支信息，故将为你中断[获取所有指定分支的详细分支信息]的操作。如您还是希望可以[获取所有指定分支的详细分支信息]，请在检查和保证 ${Develop_Branchs_FILE_PATH} 的 feature_brances 属性的值有内容后，重新执行脚本.${NC}"
    exit 0 # 只是警告，所以是 exit 0
fi


# 获取分支的详细信息
echo "\n\n"
# currentBranch=$(git branch --show-current) # 获取当前分支
printf "${YELLOW}正在执行命令(获取本分支在指定的 rebase ${REBASE_BRANCH} 分支后所含的所有分支的详细信息,然后将其设置到指定文件的指定属性 .package_merger_branchs 中)：《 ${BLUE}sh ${bulidScriptBranch_dir_Absolute}/brances_info_get.sh -envInfoF \"${Environment_FILE_PATH}\" -branchInfoF \"${Develop_Branchs_FILE_PATH}\" -rebaseBranch \"${REBASE_BRANCH}\" \"${verboseParamForSubitem}\" ${YELLOW}》${NC}\n"
sh ${bulidScriptBranch_dir_Absolute}/brances_info_get.sh -envInfoF "${Environment_FILE_PATH}" -branchInfoF "${Develop_Branchs_FILE_PATH}" -rebaseBranch "${REBASE_BRANCH}" "${verboseParamForSubitem}"
if [ $? != 0 ]; then
    commonPackageCode=$(cat ${CommonScriptResultJSONFilePath} | ${JQ_EXEC} '.package_code' | sed 's/\"//g')
    if [ "${commonPackageCode}" == "package_code_0" ]; then
        # 失败了，却在 ${CommonScriptResultJSONFilePath} 中还是成功的值，那就手动修改它(可能原因是内部没修改)
        PackageErrorCode=1
        PackageErrorMessage="brances_info_get 执行出错了。。。请查看打包日志！"
        sh "${Update_code_message_SCRIPT_PATH}" -codeMessageJsonF "${CommonScriptResultJSONFilePath}" -code "${PackageErrorCode}" -message "${PackageErrorMessage}"
        if [ $? != 0 ]; then
            echo "❌Error:${PackageErrorMessage}"
        fi
    fi
    # echo "❌Errror:出错命令如下:《 ${BLUE}sh ${bulidScriptBranch_dir_Absolute}/brances_info_get.sh -envInfoF \"${Environment_FILE_PATH}\" -branchInfoF \"${Develop_Branchs_FILE_PATH}\" -rebaseBranch \"${REBASE_BRANCH}\" \"${verboseParamForSubitem}\" ${YELLOW}》${NC}"
    exit_script
fi


# 检查提测、测试、通过后等不同阶段分支的详细信息,如提测时json中的提测时间字段必须有值
function checkBranchInfoPropertyForDiffState() {
    PackageNetworkType=$(cat $Environment_FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')

    printf "${YELLOW}正在执行命令(检查提测、测试、通过后等不同阶段分支的详细信息,如提测时json中的提测时间字段必须有值)：《 ${BLUE}sh ${qbase_branchMapsFile_checkMap_script_path} -branchMapsJsonF \"${Develop_Branchs_FILE_PATH}\" -ignoreCheckBranchNames \"${ignoreCheckBranchNameArray[*]}\" -pn \"${PackageNetworkType}\" ${YELLOW}》${NC}\n"
    checkErrorMessage=$(sh ${qbase_branchMapsFile_checkMap_script_path} -branchMapsJsonF "${Develop_Branchs_FILE_PATH}" -ignoreCheckBranchNames "${ignoreCheckBranchNameArray[*]}" -pn "${PackageNetworkType}")
    if [ $? != 0 ]; then
        echo "❌Errror:brances_info_check 执行出错了。。。$checkErrorMessage"
        exit_script
    fi
    debug_log "获取并检查分支的详细信息成功，继续执行"
    echo "\n"
}
echo "\n\n"
if [ "${ignoreCheckBranchNameArray}" == "ignoreAllCheck" ]; then
    printf "${YELLOW}温馨提示:由于您设置了 ${BLUE}-ignoreAddJsonFileNames${YELLOW} 为 ${BLUE}ignoreAllCheck ${YELLOW}，所以不用检查提测、测试、通过后等不同阶段分支的详细信息.${NC}\n"
else
    checkBranchInfoPropertyForDiffState
fi


# 提前检查分支文件是否设置正确，避免后面打包成功后去打印log的时候，才发现文件未设置正确
Develop_Branchs_FILE_PATH=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.developBranchsJsonFile' | sed 's/\"//g')
if [ $? != 0 ]; then
    echo "❌Error:获取developBranchsJsonFile失败"
    exit_script
fi
if [ ! -f "${Develop_Branchs_FILE_PATH}" ];then
    PackageErrorCode=-1
    PackageErrorMessage="您的Develop_Branchs_FILE_PATH=${Develop_Branchs_FILE_PATH}文件不存在，会导致等下打印log时候无法获取本次打包的分支信息，请检查！"
    sh "${Update_code_message_SCRIPT_PATH}" -codeMessageJsonF "${CommonScriptResultJSONFilePath}" -code "${PackageErrorCode}" -message "${PackageErrorMessage}"
    if [ $? != 0 ]; then
        echo "❌Error:${PackageErrorMessage}"
    fi
    exit_script
fi